// https://leetcode.cn/problems/shortest-common-supersequence/

// https://leetcode.cn/problems/shortest-common-supersequence/solution/python3javacgo-yi-ti-yi-jie-dong-tai-gui-uaeb/
// 类似最长公共子序列+打印路径，打印时需要把两个字符串多余的部分打出来
class Solution {
public:
    string shortestCommonSupersequence(string str1, string str2) {
        int n = str1.length();
        int m = str2.length();
        vector<vector<int>> res(n + 1, vector<int>(m + 1));
        vector<vector<int>> rec(n + 1, vector<int>(m + 1));
        
        for (int i = 0; i < n + 1; ++i)
        {
            for (int j = 0; j < m + 1; ++j)
            {
                if (i == 0 || j == 0)
                {
                    res[i][j] = 0;
                    continue; //别忘了！
                }
                res[i][j] = max(res[i][j - 1], res[i - 1][j]);
                if (res[i][j] == res[i][j - 1])
                    rec[i][j] = 1;
                else 
                    rec[i][j] = 2;
                if (str1[i - 1] == str2[j - 1])
                {
                    res[i][j] = max(res[i][j], res[i - 1][j - 1] + 1);
                    if (res[i][j] == res[i - 1][j - 1] + 1)
                        rec[i][j] = 3;
                }
            }
        }
        
        // vector<char> path(res[n][m]);
        // int p = res[m][n] - 1;
        int i = n;
        int j = m;
        string s;
        while (i > 0 && j > 0)
        {
            if (rec[i][j] == 3)
            {
                s += str1[i - 1];
                i--;
                j--;
            }
            else if (rec[i][j] == 2) 
            {
                s += str1[i - 1];
                i--;
            }
            else
            {
                s += str2[j - 1];
                j--;
            }
        }
        reverse(s.begin(), s.end());
        if (i > 0) s.insert(0, str1.substr(0, i));
        if (j > 0) s.insert(0, str2.substr(0, j));
        return s;
    }
};